//
//  ViewController.m
//  全选和单选
//
//  Created by 胡高广 on 2017/9/18.
//  Copyright © 2017年 jinshuaier. All rights reserved.
//

#import "Zz_sintonAllCheckVC.h"

#import "Zz_MobConTactsCell.h"
#import "UILabel+MyLable.h"
#import "Zz_Product.h"

#define XMGRGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define WIDTH ([UIScreen  mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define MJRandomData [NSString stringWithFormat:@"随机数据---%d", arc4random_uniform(100)]

@interface Zz_sintonAllCheckVC ()<UITableViewDelegate,UITableViewDataSource>

{
    //数据得数据源
    NSMutableArray *dataArray;
    
    //全选按钮
    UIButton *selectAll;
    
    //是否全选
    BOOL isSelect;
    
    //已选的商品合集
    NSMutableArray *selectGoods;
    NSMutableArray *_arrContacts;
}

@property (nonatomic, strong) UITableView *hggTableView;


@property (nonatomic, strong) UILabel *countLable;

@property (nonatomic, strong) NSArray<SYContacter *> *contactsArray;

@property (nonatomic, strong) UIButton *rmButton;
@end

@implementation Zz_sintonAllCheckVC

- (void)viewWillAppear:(BOOL)animated
{
    //每次进入通讯录的时候把选择的置空
    [selectGoods removeAllObjects];
    isSelect = NO;
    selectAll.selected = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //配置导航条
    [self setNav];
    self.navigationItem.title=@"通讯录";

    //初始化数组
    dataArray = [[NSMutableArray alloc] init];
    selectGoods = [[NSMutableArray alloc] init];

    ///获取所有通讯录
    [self getContactsAllArray];
    //配置tableView
    [self createTableView];
}

-(void)getContactsAllArray{
    __weak Zz_sintonAllCheckVC *weakSelf = self;
    [SYContactsHelper fetchContacts:^(NSArray <SYContacter *> *contacts, BOOL success) {
        if (success) {
            //[weakSelf reloadContacts:contacts];

            _contactsArray=contacts;
            if (contacts.count>0) {

            }else{
                self.rmButton.enabled=NO;
                self.rmButton.backgroundColor=[UIColor lightGrayColor];
            }

            [self.hggTableView reloadData];
        }
        else {
            [weakSelf showUserDenied];
        }
    }];
}
//配置tableView
- (void)createTableView
{


    self.rmButton = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH-WIDTH/2)/2, HEIGHT-50, WIDTH/2, 40)];

    [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人"] forState:UIControlStateNormal];

    self.rmButton.backgroundColor=[UIColor lightGrayColor];
    [self.rmButton addTarget:self action:@selector(removeAllContacts:) forControlEvents:UIControlEventTouchUpInside];
    self.rmButton.enabled=NO;

    [self.view addSubview:self.rmButton];


    self.hggTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-60) style:UITableViewStylePlain];
    self.hggTableView.delegate =self;
    self.hggTableView.dataSource = self;
    self.hggTableView.showsVerticalScrollIndicator = NO;
    self.hggTableView.separatorStyle = 0;
    self.hggTableView.rowHeight = 50;
    [self.view addSubview:self.hggTableView];



    //创建头部视图
}

#pragma mark -- 全选按钮的点击事件
- (void)selectAllBtnClick:(UIButton *)button
{
    //点击全选时，把之前已选择的全部删除
    [selectGoods removeAllObjects];
    self.rmButton.enabled=YES;
    self.rmButton.backgroundColor=XMGRGBColor(0,222,33);
    button.selected = !button.selected;
    isSelect = button.selected;
    
    //如果选择了
    if (isSelect) {
        for (SYContacter *model in _contactsArray) {
            [selectGoods addObject:model];

            self.rmButton.enabled=YES;
            self.rmButton.backgroundColor=XMGRGBColor(0,222,33);
            [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人(%zd)",selectGoods.count] forState:UIControlStateNormal];
        }
    }
    else
    {
        [selectGoods removeAllObjects];

        self.rmButton.enabled=NO;
        self.rmButton.backgroundColor=[UIColor lightGrayColor];
        [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人"] forState:UIControlStateNormal];
    }
    
    //刷新
    [self.hggTableView reloadData];
}


#pragma mark -- tableview的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _contactsArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Zz_MobConTactsCell *hggCell  = [Zz_MobConTactsCell cellWithTableView:tableView];
    hggCell.isSelected = isSelect;
    
    //是否被选中
    if ([selectGoods containsObject:[_contactsArray objectAtIndex:indexPath.row]])
    {
        hggCell.isSelected = YES;
    }
    
    //block的实现方法
    hggCell.cartBlock = ^(BOOL isSelec){


        //选中就加入到数组
        if (isSelec) {

            [selectGoods addObject:[_contactsArray objectAtIndex:indexPath.row]];
 
            NSLog(@" %zd",selectGoods.count);

            if (selectGoods.count==0) {
                self.rmButton.enabled=NO;
                [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人"] forState:UIControlStateNormal];
            }else{

                self.rmButton.enabled=YES;
                self.rmButton.backgroundColor=XMGRGBColor(0,222,33);

                [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人(%zd)",selectGoods.count] forState:UIControlStateNormal];

            }
        }
        else
        {
            //移除
            [selectGoods removeObject:[_contactsArray objectAtIndex:indexPath.row]];
            if (selectGoods.count==0) {

                self.rmButton.enabled=NO;

                [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人"] forState:UIControlStateNormal];
            }else{
                [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人(%zd)",selectGoods.count] forState:UIControlStateNormal];
            }
        }
        
        //全选了
        if (selectGoods.count == _contactsArray.count) {
            selectAll.selected = YES;
        }
        else
        {
            selectAll.selected = NO;
        }
        
    };
    hggCell.addressBook=_contactsArray[indexPath.row];


    return hggCell;
}

#pragma mark -===== 移除所有/选中的 通讯录
-(void)removeAllContacts:(UIButton *)sender{

        for (SYContacter *tmpPerson in selectGoods) {

            NSString *name=tmpPerson.name;

                ABAddressBookRef tmpAddressBook = ABAddressBookCreate();
                NSArray* tmpPersonArray = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(tmpAddressBook);
                for(id tmpPerson in tmpPersonArray)
                {
                    NSString* tmpFirstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonFirstNameProperty);
                    NSString* tmpLastName  = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonLastNameProperty);
                    NSString* tmpFullName = [NSString stringWithFormat: @"%@%@", [tmpFirstName lowercaseString], [tmpLastName lowercaseString]];

                    //删除联系人

                    if([tmpFullName isEqualToString:name]||[tmpFirstName isEqualToString:name]||[tmpLastName isEqualToString:name])
                    {
                        ABAddressBookRemoveRecord(tmpAddressBook, (__bridge ABRecordRef)(tmpPerson), nil);

                    }
                }
                //保存电话本
                ABAddressBookSave(tmpAddressBook, nil);
                //释放内存
                CFRelease(tmpAddressBook);
            }

   isSelect = NO;
    [self getContactsAllArray];

}

#pragma mark ---配置导航条
- (void)setNav{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *additionBtn = [[UIButton alloc] init];
    [additionBtn setTitle:@"全选" forState:UIControlStateNormal];
    additionBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [additionBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [additionBtn addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    additionBtn.frame = CGRectMake(0, 0, 40, 25);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:additionBtn];
}


#pragma mark === 显示拒绝信息
- (void)showUserDenied {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.textColor = [UIColor redColor];
    [self.view addSubview:label];

    NSString *str = [NSString stringWithFormat:@"您没有权限访问通讯录\n\n请到“设置-隐私-通讯录”里\n允许”SYContactsPicker“访问"];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:[str rangeOfString:@"您没有权限访问通讯录"]];
    label.attributedText = attributedString;
    [label sizeToFit];
    label.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height);
    label.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);

    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.frame = CGRectMake(0, 0, 140, 40);
    settingBtn.backgroundColor = [UIColor blueColor];
    settingBtn.layer.cornerRadius = 5;
    settingBtn.layer.masksToBounds = YES;
    [settingBtn setTitle:@"去设置" forState:UIControlStateNormal];
    [settingBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    settingBtn.center = CGPointMake(self.view.frame.size.width / 2, label.center.y + 5 + 20 + label.frame.size.height / 2);
    [settingBtn addTarget:self action:@selector(onClickBtnSetting:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingBtn];
}


- (void)onClickBtnSetting:(UIButton *)btn {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root"]];
}
@end
